package com.qf.blog.web.controller;

import com.qf.blog.core.exception.JsonException;
import com.qf.blog.core.utils.R;
import com.qf.blog.web.entity.UserEntity;
import com.qf.blog.web.service.impl.LikeService;
import com.qf.blog.web.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/like")
public class LikeController {

    @Autowired
    private LikeService likeService;

    @PostMapping("/clickLike")
    public R clickLike(@RequestBody LikeVo likeVo, HttpSession session) {

        // 1.判断用户是否登录
        UserEntity userEntity = (UserEntity) session.getAttribute("loginUser");
        if (userEntity == null) {
            throw new JsonException(301, "请先登录");
        }

        likeVo.setUserId(userEntity.getId());

        // 2.调用业务层实现点赞
        likeService.clickLike(likeVo); // 返回是否点赞

        // 再次查询是否点赞
        Boolean isLike = likeService.isLike(likeVo);

        // 3.查询最新的点赞数量
        Long likeCount = likeService.getInvitataionLikeCount(likeVo.getEntityType(), likeVo.getEntityId());

        R ok = R.ok();
        ok.put("likeStatus", isLike ? 1 : 0);
        ok.put("likeCount", likeCount);
        return ok;
    }
}
